<template>
    <div class="container mt-2">
        <!-- 
        :before-upload="beforeAvatarUpload"
        -->
        <el-upload class="avatar-uploader" action="#" :limit="1" :on-change="fileChange"
            :on-exceed="() => ElMessage.warning('最多只能上传一张图片')" :auto-upload="false" list-type="picture-card">
            <el-icon class="avatar-uploader-icon">
                <Plus />
            </el-icon>
        </el-upload>
        <el-divider></el-divider>
        <el-button @click="submit" type="primary">立即上传</el-button>
    </div>
</template>
<script setup>
import http from '@/utils/http'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { onMounted, ref } from 'vue'
const router = useRouter
let avatar = null
const loginInfo = ref({})
const fileChange = (file) => {
    avatar = file.raw
}
const submit = async () => {
    const fd = new FormData()
    fd.append('avatar', avatar)
    const result = await http.patch('/api/userinfo/update_avatar/', fd)
    if (result.status === 200) {
        router.push({ name: 'ucenter' })
    }

}
onMounted(async () => {
    const loginData = localStorage.getItem('loginInfo')
    if (!loginData) {
        const res = await http.post('/api/userinfo/login_info/')
        if (res.status === 200) {
            loginInfo.value = res.data
            localStorage.setItem('loginInfo', JSON.stringify(res.data))
        }
        return false
    }
    loginInfo.value = JSON.parse(loginData || '{}')
})
</script>
<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>